package com.wsc.it.utils;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.wsc.it.bridge.vo.LrReceiptPrint;
import com.wsc.it.bridge.vo.MothPrinterAndStore;
import com.wsc.it.bridge.vo.ShopOrderGoodsOSM;
import com.wsc.it.bridge.vo.ShopOrderNum;
import com.wsc.it.bridge.vo.ShopOrderOSM;

import cn.hutool.core.date.DateUtil;

public   class PrinterUtil {
	private static final Logger log = LoggerFactory.getLogger(PrinterUtil.class);

    public static final String FEIEYUN_URL = "http://api.feieyun.cn/Api/Open/";//不需要修改
    public static final Integer WIDTH = 32;//打印纸的宽度

    public static final String QR_H5 = "https://wechat.lirimall.com/#/h5.html";//二维码地址
    public static final String USER = "";//*必填*：账号名
    public static final String UKEY = "";//*必填*: 飞鹅云后台注册账号后生成的UKEY 【备注：这不是填打印机的KEY】
//    public static final String SN = "930503936";//*必填*：打印机编号，必须要在管理后台里添加打印机或调用API接口添加之后，才能调用API

    //查询已成功打印的次数
    public static final  Integer alreadyPrintCount =1;

    
    //商超订单打印
    public String printShangChao(ShopOrderOSM shopOrderOSM, MothPrinterAndStore mothPrinterAndStore, LrReceiptPrint receiptPrint) {
         
        String resStr = null;
        //商家联
        if (receiptPrint.getMerchantSwitch() == 1) {
        	List<String> merchantContents = getOrderShangChaoMerchantLeague(shopOrderOSM, alreadyPrintCount);
        	int times =Integer.parseInt(receiptPrint.getMerchantLeague()) ;
        	for (int i = 0; i <times  ; i++) {
    			for (int j = 0; j < merchantContents.size(); j++) {
    				if(!StringUtils.isEmpty(merchantContents.get(j))) {
    					log.info("i-j 商家联打印信息：{}--{} {}" ,i,j,merchantContents.get(j));
    					String resMerchantStr=	this.print(merchantContents.get(j), mothPrinterAndStore.getMothPrinterSn(), "1");
    					log.info("飞鹅云小票商家联打印返回信息:{}",resMerchantStr);
    					resStr+=resMerchantStr;
    					
    				}
    			}
    		}
        }
        //买家联
        if (receiptPrint.getCustomerSwitch() == 1) {
        
        	List<String> customerContents = getOrderShangChaoCustomerLeague(shopOrderOSM, alreadyPrintCount);
        	int times =Integer.parseInt(receiptPrint.getCustomerLeague()) ;
        	for (int i = 0; i <times  ; i++) {
    			for (int j = 0; j < customerContents.size(); j++) {
    				if(!StringUtils.isEmpty(customerContents.get(j))) {
	    				log.info("买家联打印信息：{}--{} {}" ,i,j,customerContents.get(j));
	    				String resCustomerStr = this.print(customerContents.get(j), mothPrinterAndStore.getMothPrinterSn(), "1");
	    			    log.info("飞鹅云小票买家联打印返回信息:{}",resCustomerStr);
	    			    resStr+=resCustomerStr;
    				}
    			}
    		}
        
        }
        
        
        log.info(" {} 飞鹅云小票商家联打印返回信息:{}",shopOrderOSM.getOrderNumber(),resStr);
        return null;
    }
 

    
    //打印
    public String print(String content, String mothPrinterSn, String times) {
    
    	//通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpPost post = new HttpPost(FEIEYUN_URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user", USER));
        String STIME = String.valueOf(System.currentTimeMillis() / 1000);
        nvps.add(new BasicNameValuePair("stime", STIME));
        nvps.add(new BasicNameValuePair("sig", signature(USER, UKEY, STIME)));
        nvps.add(new BasicNameValuePair("apiname", "Open_printMsg"));//固定值,不需要修改
        nvps.add(new BasicNameValuePair("sn", mothPrinterSn));
        nvps.add(new BasicNameValuePair("content", content));
        nvps.add(new BasicNameValuePair("times", times + ""));//打印联数

        CloseableHttpResponse response = null;
        String result = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if (statecode == 200) {
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null) {
                    //服务器返回的JSON字符串，建议要当做日志记录起来
                    result = EntityUtils.toString(httpentity);
                }
            }
        } catch (Exception e) {
        	log.error("请求飞鹅打印小票失败：{}",e.getMessage());
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
     //58mm的机器,一行打印16个汉字,32个字母; 
	private List<String> getOrderShangChaoMerchantLeague(ShopOrderOSM shopOrderOSM,  Integer alreadyPrintCount) {
		//b1代表名称列占用字节  b2单价列 b3数量列 b4金额列-->这里的字节数可按自己需求自由改写， 
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<String> contents=new ArrayList<String>();
        
        //门店信息
        String storeName=shopOrderOSM.getStoreName() ;
        //小票号
        String printNumber= shopOrderOSM.getPrintNumber() == null ? "0" : ""+shopOrderOSM.getPrintNumber();
        //配送类型
        String deliveryTypeStr=  (shopOrderOSM.getDeliveryType() == 0 ? "配送到家" : "到店自提") ;
        //运费
        String deliveryFeeStr= "" ;
        String freightStr= "" ;
        //预约配送时间
        String estimatedDeliveryTime= "" ;
        if(shopOrderOSM.getDeliveryType()==0) {
        	deliveryFeeStr="配送金额：<RIGHT>" + shopOrderOSM.getDeliveryFee() + "</RIGHT><BR>";
        	freightStr="减免运费：<RIGHT>-" + shopOrderOSM.getFreight()+ "</RIGHT><BR>";
        	if(shopOrderOSM.getEstimatedDeliveryStartTime()!=null) {
        		try {
        			estimatedDeliveryTime += "<BOLD><CB>预约配送时间:</BOLD></CB><BR>";
        			estimatedDeliveryTime	+= "<BOLD><B>" +DateUtil.format(shopOrderOSM.getEstimatedDeliveryStartTime(),"yyyy-MM-dd HH:mm")
            		+"~"+DateUtil.format(shopOrderOSM.getEstimatedDeliveryEndTime(),"HH:mm")+ "</B></BOLD><BR>";
        		}catch (Exception e) {
        			log.error("日期转换错误：{}",JSON.toJSONString(shopOrderOSM));
				}
        	}
        } 
        
        String contentStart;
        
        contentStart = "<BOLD><CB>商家联</CB></BOLD><BR>";//居中放大 字体加粗
        contentStart += "<B><BOLD>丽日购     #"+ printNumber + "</B><BOLD><BR>";
        contentStart +="丽日超市("+storeName + ")<BR>";
        contentStart += "<BOLD><CB>"+deliveryTypeStr+ "</CB></BOLD><BR>";//居中放大 字体加粗
        if (alreadyPrintCount > 0) {
        	contentStart += "<BOLD><CB>(重复打印)</CB></BOLD><BR>";
        }
        
        contentStart += estimatedDeliveryTime;//居中放大 字体加粗
        contentStart += "订单编号：" + shopOrderOSM.getOrderNumber() + "<BR>";
        contentStart += "名称           数量  单价 金额<BR>";
        contentStart += "<C>-------------商品--------------</C><BR>";
        
        BigDecimal goodsNums = new BigDecimal(0);
        BigDecimal actualPrices = new BigDecimal(0);
        List<ShopOrderGoodsOSM> list = shopOrderOSM.getList();
     
        for (int i = 0; i < list.size(); i++) {
        	ShopOrderGoodsOSM	entity	=shopOrderOSM.getList().get(i);
            String title =(i+1)+"."+ entity.getGoodsName();
            String otherStr = "";
            List<ShopOrderNum> shopOrderNums = entity.getShopOrderNums();
            for (ShopOrderNum goodsNum : shopOrderNums) {
                String price = goodsNum.getPrice().toString();
                String num = goodsNum.getPurchaseQuantity().toString();
                String total = "" + goodsNum.getPrice().multiply(BigDecimal.valueOf(goodsNum.getPurchaseQuantity())).setScale(2, RoundingMode.HALF_UP).toString();
                otherStr = otherStr + "<BOLD>x【" + num + "】   " +price+ "   " + total+"</BOLD>";
                actualPrices = actualPrices.add(goodsNum.getPrice().multiply(BigDecimal.valueOf(goodsNum.getPurchaseQuantity())));
            }
            contentStart += "<BOLD>"+title +"</BOLD><BR>";
            contentStart += "<RIGHT>"+otherStr +"</RIGHT><BR>";
            
            contentStart += "UPC码：" + entity.getGoodsBarcode() + " <BR>";
            contentStart += "SKU码：" + entity.getGoodsCode() + " <BR><BR>";
            goodsNums = goodsNums.add(entity.getGoodsNum());
        
        	
            if(contentStart.getBytes().length>=4500) {
            	contents.add(contentStart);
            	contentStart="";
            } 
        }
    	
        contentStart += "================================<BR>";
        contentStart += "<BOLD>总件数：" + goodsNums.setScale(0, RoundingMode.HALF_UP) + "</BOLD><BR>";
        contentStart += "商品总金额：<RIGHT>" + actualPrices.setScale(2, RoundingMode.HALF_UP) + "</RIGHT><BR>";
        contentStart += deliveryFeeStr;
        contentStart +=freightStr; 
        contentStart += "优惠券减免金额：<RIGHT>-" + shopOrderOSM.getReductionAmount() + "</RIGHT><BR>";
        contentStart += "惠购券：<RIGHT>-" + shopOrderOSM.getHgoCouponReduce() + "</RIGHT><BR>";
        contentStart += "打包费：<RIGHT>" + shopOrderOSM.getPackingFee() + "</RIGHT><BR>";
        contentStart += "--------------------------------<BR>";
        contentStart += "实付：<B><RIGHT>" + (shopOrderOSM.getActualPay() == null ? "0.00" : shopOrderOSM.getActualPay()) + "元</RIGHT></B><BR>";
        contentStart += "--------------------------------<BR>";
        if (shopOrderOSM.getDeliveryType() == 0) {
        	contentStart += "<BOLD>【" + shopOrderOSM.getLinkman() + "】</BOLD><BR>";
        	contentStart += "<BOLD>联系电话：" + shopOrderOSM.getTelephone() + "</BOLD><BR>";
        	contentStart += "送货地点：" + shopOrderOSM.getAddress() + "<BR>";
        } else if (shopOrderOSM.getDeliveryType() == 1) {
        	contentStart += "<BOLD>预留电话：" + shopOrderOSM.getPickUpPhone() + "</BOLD><BR>";
        	contentStart += "<BOLD>下单用户的手机：" + shopOrderOSM.getTelephone() + "</BOLD><BR>";
            contentStart += "<BOLD>自提截止时间：" + sdf.format(shopOrderOSM.getPickUpLimit()) + "</BOLD><BR>";
        }
        contentStart += "下单时间：" + sdf.format(shopOrderOSM.getCreateTime()) + "<BR>";
        if (StringUtils.isEmpty(shopOrderOSM.getRemark())) {
        	contentStart += "备注：<BR>";
        } else {
        	contentStart += "备注：" + shopOrderOSM.getRemark() + "<BR>";
        }
        contents.add(contentStart);
        
		return contents;
	}

   
	private  List<String> getOrderShangChaoCustomerLeague(ShopOrderOSM shopOrderOSM, Integer alreadyPrintCount) {
	 
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<String> contents=new ArrayList<String>();
        
        String contentStart;
        //门店信息
        String storeName=shopOrderOSM.getStoreName() ;
        //小票号
        String printNumber= shopOrderOSM.getPrintNumber() == null ? "0" : ""+shopOrderOSM.getPrintNumber();
        //配送类型
        String deliveryTypeStr=  (shopOrderOSM.getDeliveryType() == 0 ? "配送到家" : "到店自提") ;
        //运费
        String deliveryFeeStr= "" ;
        String freightStr= "" ;
        if(shopOrderOSM.getDeliveryType()==0) {
        	deliveryFeeStr="配送金额：<RIGHT>" + shopOrderOSM.getDeliveryFee() + "</RIGHT><BR>";
        	freightStr="减免运费：<RIGHT>-" + shopOrderOSM.getFreight()+ "</RIGHT><BR>";
        } 
        contentStart = "<BOLD><CB>买家联</CB></BOLD><BR>";//居中放大 字体加粗
        contentStart += "<B><BOLD>丽日购     #"+ printNumber + "</B><BOLD><BR>";
        contentStart +="丽日超市("+storeName + ")<BR>";
        contentStart += "<BOLD><CB>"+deliveryTypeStr+ "</CB></BOLD><BR>";//居中放大 字体加粗
        if (alreadyPrintCount > 0) {
        	contentStart += "<BOLD><CB>(重复打印)</CB></BOLD><BR>";
        }
        
        contentStart += "订单编号：" + shopOrderOSM.getOrderNumber() + "<BR>";
        contentStart += "名称           数量  单价 金额<BR>";
        contentStart += "<C>-------------商品--------------</C><BR>";
        BigDecimal goodsNums = new BigDecimal(0);
        BigDecimal actualPrices = new BigDecimal(0);
        List<ShopOrderGoodsOSM> list = shopOrderOSM.getList();
        
        for (int i = 0; i < list.size(); i++) {
        	ShopOrderGoodsOSM	entity	=shopOrderOSM.getList().get(i);
            String title =(i+1)+"."+ entity.getGoodsName();
            String otherStr = "";
            List<ShopOrderNum> shopOrderNums = entity.getShopOrderNums();
            for (ShopOrderNum goodsNum : shopOrderNums) {
                String price = goodsNum.getPrice().toString();
                String num = goodsNum.getPurchaseQuantity().toString();
                String total = "" + goodsNum.getPrice().multiply(BigDecimal.valueOf(goodsNum.getPurchaseQuantity())).setScale(2, RoundingMode.HALF_UP).toString();
                otherStr = otherStr + "<BOLD>x【" + num + "】   " +price+ "   " + total+"</BOLD>";
                actualPrices = actualPrices.add(goodsNum.getPrice().multiply(BigDecimal.valueOf(goodsNum.getPurchaseQuantity())));
            }
            contentStart += "<BOLD>"+title +"</BOLD><BR>";
            contentStart += "<RIGHT>"+otherStr +"</RIGHT><BR>";
            
            contentStart += "UPC码：" + entity.getGoodsBarcode() + " <BR>";
            contentStart += "SKU码：" + entity.getGoodsCode() + " <BR><BR>";
            goodsNums = goodsNums.add(entity.getGoodsNum());
            if(contentStart.getBytes().length>=4500) {
            	contents.add(contentStart);
            	contentStart="";
            } 
            
        }
        
        
        contentStart += "================================<BR>";
        contentStart += "<BOLD>总件数：" + goodsNums.setScale(0, RoundingMode.HALF_UP) + "</BOLD><BR>";
        contentStart += "商品总金额：<RIGHT>" + actualPrices.setScale(2, RoundingMode.HALF_UP) + "</RIGHT><BR>";
        contentStart += "配送金额：<RIGHT>" + shopOrderOSM.getDeliveryFee() + "</RIGHT><BR>";
        contentStart += deliveryFeeStr;
        contentStart +=freightStr; 
        contentStart += "优惠券减免金额：<RIGHT>-" + shopOrderOSM.getReductionAmount() + "</RIGHT><BR>";
        contentStart += "惠购券：<RIGHT>-" + shopOrderOSM.getHgoCouponReduce() + "</RIGHT><BR>";
        contentStart += "打包费：<RIGHT>" + shopOrderOSM.getPackingFee() + "</RIGHT><BR>";
        contentStart += "--------------------------------<BR>";
        contentStart += "实付：<B><RIGHT>" + (shopOrderOSM.getActualPay() == null ? "0.00" : shopOrderOSM.getActualPay()) + "元</RIGHT></B><BR>";
    	contentStart += "--------------------------------<BR>";
        if (shopOrderOSM.getDeliveryType() == 0) {
        	contentStart += "<BOLD>【" + shopOrderOSM.getLinkman() + "】</BOLD><BR>";
        	contentStart += "<BOLD>联系电话：" + shopOrderOSM.getTelephone() + "</BOLD><BR>";
            contentStart += "送货地点：" + shopOrderOSM.getAddress() + "<BR>";
        } else if (shopOrderOSM.getDeliveryType() == 1) {
        	contentStart += "<BOLD>预留电话：" + shopOrderOSM.getPickUpPhone() + "</BOLD><BR>";
            contentStart += "<BOLD>下单用户的手机：" + shopOrderOSM.getTelephone() + "</BOLD><BR>";
            contentStart += "<BOLD>自提截止时间：" + sdf.format(shopOrderOSM.getPickUpLimit()) + "</BOLD><BR>";
        }
        contentStart += "下单时间：" + sdf.format(shopOrderOSM.getCreateTime()) + "<BR>";
        if (StringUtils.isEmpty(shopOrderOSM.getRemark())) {
            contentStart += "备注：<BR>";
        } else {
            contentStart += "备注：" + shopOrderOSM.getRemark() + "<BR>";
        }
        contentStart += "<QR>"+QR_H5+"</QR>";
        contents.add(contentStart);
        
      	return contents;
	}

    
    //生成签名字符串
    private static String signature(String USER, String UKEY, String STIME) {
        String s = DigestUtils.sha1Hex(USER + UKEY + STIME);
        return s;
    }


   
    
     
}



